#!/usr/bin/env python3
"""
迭代器模式与生成器的关系演示
"""

# 传统迭代器实现
class FibonacciIterator:
    def __init__(self, max_count=None):
        self.a, self.b = 0, 1
        self.count = 0
        self.max_count = max_count
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.max_count and self.count >= self.max_count:
            raise StopIteration
        
        current = self.a
        self.a, self.b = self.b, self.a + self.b
        self.count += 1
        return current

# 生成器实现
def fibonacci_generator(max_count=None):
    a, b = 0, 1
    count = 0
    while True:
        if max_count and count >= max_count:
            return
        yield a
        a, b = b, a + b
        count += 1

# 生成器实现: 无限循环
def fib_simple():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b


# 测试代码
if __name__ == "__main__":
    print("=== 传统迭代器 ===")
    fib_iter = FibonacciIterator(10)
    for num in fib_iter:
        print(num, end=" ")
    
    print("\n\n=== 生成器 ===")
    fib_gen = fibonacci_generator(10)
    for num in fib_gen:
        print(num, end=" ")
    
    print("\n\n=== 生成器表达式 ===")
    # 生成器表达式也是迭代器
    squares = (x*x for x in range(10))
    print("生成器类型:", type(squares))
    print("是否迭代器:", hasattr(squares, '__iter__'))
    print("是否可迭代:", hasattr(squares, '__next__'))
    
    print("\n=== 验证生成器是迭代器 ===")
    import collections.abc
    gen = fibonacci_generator(5)
    print("生成器是迭代器:", isinstance(gen, collections.abc.Iterator))
    print("生成器是可迭代对象:", isinstance(gen, collections.abc.Iterable))